{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "from typing import List\n",
    "import random\n",
    "import sys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "def encrypt_message(key: int, message: str) -> str:\n",
    "    \"\"\"\n",
    "    使用列置换加密消息\n",
    "    \n",
    "    Args:\n",
    "        key: 加密密钥(列数)\n",
    "        message: 要加密的明文\n",
    "        \n",
    "    Returns:\n",
    "        加密后的密文字符串\n",
    "    \"\"\"\n",
    "    # 创建列容器\n",
    "    ciphertext_columns: List[str] = [''] * key\n",
    "    \n",
    "    # 填充各列\n",
    "    for column in range(key):\n",
    "        for current_index in range(column, len(message), key):\n",
    "            ciphertext_columns[column] += message[current_index]\n",
    "    \n",
    "    return ''.join(ciphertext_columns)\n",
    "'''\n",
    "def encrypt_message(key: int, message: str) -> str:\n",
    "    ciphertext_columns = [''] * key\n",
    "    column = 0\n",
    "    for symbol in message:\n",
    "        ciphertext_columns[column] += symbol\n",
    "        column += 1\n",
    "        if column == key:\n",
    "            column = 0\n",
    "    return ''.join(ciphertext_columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4",
   "metadata": {},
   "outputs": [],
   "source": [
    "def decrypt_message(key: int, message: str) -> str:\n",
    "    \"\"\"\n",
    "    列置换解密算法\n",
    "    \n",
    "    参数:\n",
    "        key: 解密密钥(原始加密时的列数)\n",
    "        message: 要解密的密文\n",
    "        \n",
    "    返回:\n",
    "        解密后的明文字符串\n",
    "    \"\"\"\n",
    "    # 计算解密表格参数\n",
    "    num_columns = math.ceil(len(message) / key)\n",
    "    num_rows = key\n",
    "    shaded_boxes = (num_columns * num_rows) - len(message)\n",
    "\n",
    "    # 初始化列容器\n",
    "    plaintext_columns: List[str] = [''] * num_columns\n",
    "    column, row = 0, 0\n",
    "\n",
    "    for symbol in message:\n",
    "        plaintext_columns[column] += symbol\n",
    "        column += 1\n",
    "\n",
    "        # 检查是否需要换行\n",
    "        if (column == num_columns) or \\\n",
    "           (column == num_columns - 1 and row >= num_rows - shaded_boxes):\n",
    "            column = 0\n",
    "            row += 1\n",
    "\n",
    "    return ''.join(plaintext_columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_random_message() -> str:\n",
    "    \"\"\"生成随机测试消息\"\"\"\n",
    "    base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n",
    "    message = list(base * random.randint(4, 40))\n",
    "    random.shuffle(message)\n",
    "    return ''.join(message)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def test_encryption_roundtrip(message: str, max_key_size: int) -> bool:\n",
    "    \"\"\"测试单个消息的加密-解密往返\"\"\"\n",
    "    for key in range(1, max_key_size + 1):\n",
    "        encrypted = encrypt_message(key, message)\n",
    "        decrypted = decrypt_message(key, encrypted)\n",
    "        \n",
    "        if message != decrypted:\n",
    "            print(f\"❌ 测试失败 - 密钥: {key}\")\n",
    "            print(f\"原始消息: {message[:50]}...\")\n",
    "            print(f\"解密结果: {decrypted[:50]}...\")\n",
    "            return False\n",
    "    return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_test_suite(num_tests: int = 20) -> None:\n",
    "    \"\"\"运行完整的测试套件\"\"\"\n",
    "    random.seed(42)  # 固定种子确保可重复性\n",
    "    \n",
    "    for test_num in range(1, num_tests + 1):\n",
    "        message = generate_random_message()\n",
    "        max_key = max(1, len(message) // 2 - 1)  # 确保密钥至少为1\n",
    "        \n",
    "        print(f\"🔍 测试 #{test_num:2d}: {message[:50]}... (长度: {len(message)}, 最大密钥: {max_key})\")\n",
    "        \n",
    "        if not test_encryption_roundtrip(message, max_key):\n",
    "            sys.exit(1)\n",
    "    \n",
    "    print(\"✅ 置换密码测试全部通过\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8",
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test_suite()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
